package com.health.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.health.constant.Constants;
import com.health.dao.BloodSugarDAO;
import com.health.exceptions.ExportException;
import com.health.exceptions.ExportLevelException;
import com.health.model.BloodSugar;
import com.health.model.Excel;
import com.health.service.IBloodSugarService;

public class BloodSugarService implements IBloodSugarService
{

	private Log					log			= LogFactory.getLog(BloodSugarService.class);
	/** spring inject */
	private BloodSugarDAO		sugarDAO;

	/** spring inject(maxRows,path) */
	private Excel				sugarExportExcel;

	private SimpleDateFormat	formatter	= new SimpleDateFormat("yyyy-MM-dd hh-mm-ss",
													Locale.CHINA);

	@Override
	public void insert(BloodSugar s) throws ParseException
	{
		sugarDAO.insert(s);
	}

	@Override
	public void update(BloodSugar s)
	{
		sugarDAO.update(s);
	}

	@Override
	public void delete(BloodSugar s)
	{
		sugarDAO.delete(s);
	}

	@Override
	public BloodSugar selectByPK(String id)
	{
		return sugarDAO.selectByPK(id);
	}

	@Override
	public Collection<BloodSugar> selectListAll(BloodSugar s)
	{
		return sugarDAO.selectListAll(s);
	}

	@Override
	public Collection<BloodSugar> selectListPage(BloodSugar s)
	{
		return sugarDAO.selectListPage(s);
	}

	/***
	 * export the user request data to a ExcelFile,<br>
	 * (default write the file to "D\\HealthManger2.0Folder\\exportSugar") and
	 * ready to be download
	 * **/
	@Override
	public void exportExcel(BloodSugar s) throws ExportException,
			ExportLevelException
	{
		List<BloodSugar> list = (List<BloodSugar>) selectListAll(s);
		int maxRows = sugarExportExcel.getMaxRows();// spring inject
		if (list.size() > maxRows)
		{
			log.error("export data too much!out of range");
			throw new ExportException("export data too much!out of range");
		}
		Date date = new Date();
		String userId = s.getUserId();
		String filePath = sugarExportExcel.getPath();// spring inject
		String dateStr = formatter.format(date);
		sugarExportExcel.setName(dateStr + "_"
				+ (userId.substring(0, 8)).replace(".", "") + ".xls");

		try
		{
			WritableWorkbook book = Workbook.createWorkbook(new File(filePath
					+ sugarExportExcel.getName()));
			WritableSheet sheet = book.createSheet("BloodSugarSheet", 0);
			Label titleLabel = new Label(0, 0, "BloodSugarExport");
			Label titleTimeLabel = new Label(1,1,"examtime");
			Label titleAtMealLabel = new Label(2,1,"at meal");
			Label titleValueLabel = new Label(3,1,"value");
			String dateRange = "";
			if (null != s.getExamTimeStart())
			{
				dateRange = formatter.format(s.getExamTimeStart()) + "--";
			}
			if (null != s.getExamTimeEnd())
			{
				dateRange += "--" + formatter.format(s.getExamTimeEnd());
			}
			// String dateRange = formatter.format(s.getExamTimeStart())
			// .toString()
			// + "---"
			// + formatter.format(s.getExamTimeEnd()).toString();
			Label dateRangeLabel = new Label(1, 1, dateRange);
			Label userLabel = new Label(1, 2, userId);
			sheet.addCell(titleLabel);
			sheet.addCell(dateRangeLabel);
			sheet.addCell(userLabel);
			sheet.addCell(titleTimeLabel);
			sheet.addCell(titleAtMealLabel);
			sheet.addCell(titleValueLabel);
			for (int i = 0; i < list.size(); i++)
			{
				Label timeLabel = new Label(1,
						i + 2,
						formatter.format(list.get(i).getExamTime()));
				sheet.addCell(timeLabel);
				String atMeal = list.get(i).getAtMeal();
				if (atMeal.equals(Constants.BEFORE_MEAL))
				{
					atMeal = "before meal";
				}
				else if (atMeal.equals(Constants.AFTER_MEAL))
				{
					atMeal = "after meal";
				}
				Label atMealLabel = new Label(2, i + 2, atMeal);
				sheet.addCell(atMealLabel);
				Label valueLabel = new Label(3,
						i + 2,
						(list.get(i).getValue()).toString());
				sheet.addCell(valueLabel);
			}
			book.write();
			book.close();
		}
		catch (IOException e)
		{
			log.error(e);
			throw new ExportLevelException(e.getMessage(), e);
		}
		catch (RowsExceededException e)
		{
			log.error(e);
			throw new ExportLevelException(e.getMessage(), e);
		}
		catch (WriteException e)
		{
			log.error(e);
			throw new ExportLevelException(e.getMessage(), e);
		}

	}

	/***************************************************************************
	 * getters and setters
	 **************************************************************************/
	public BloodSugarDAO getSugarDAO()
	{
		return sugarDAO;
	}

	public void setSugarDAO(BloodSugarDAO sugarDAO)
	{
		this.sugarDAO = sugarDAO;
	}

	public Excel getSugarExportExcel()
	{
		return sugarExportExcel;
	}

	public void setSugarExportExcel(Excel sugarExportExcel)
	{
		this.sugarExportExcel = sugarExportExcel;
	}

}
